﻿using AutoMapper;
using MediatR;
using Reporting.API.Application.Commands.InvoiceManagements;
using Reporting.API.DTOs.InvoiceManagementResponseDto;
using Reporting.API.Utils;
using Reporting.Errorcode.ErrorCode;
using Reporting.Infrastructure.Interfaces.InvoiceManagements;
using Reporting.Infrastructure.Interfaces.Invoicetypes;
using Reporting.Infrastructure.Interfaces.Payees;

namespace Reporting.API.Application.CommandHandler.InvoiceManagements
{
    /// <summary>
    /// 显示  开票管理
    /// </summary>
    public class GetInvoiceManagementCommandHandler : IRequestHandler<GetInvoiceManagementCommand, ApiResult<PagingResult<IList<GetpageInvoiceManagementResponse>>>>
    {
        private readonly IInvoiceManagementRepository  _invoiceManagementRepository;  //开票
        private readonly IInvoicetypeRepository _invoicetypeRepository;  //发票类型
        private readonly IPayeeRepository  _payeeRepository;  //开、收票方
        private readonly IMapper _mapper;
        private readonly ILogger<GetInvoiceManagementCommandHandler> _logger;
        public GetInvoiceManagementCommandHandler(IInvoiceManagementRepository invoiceManagementRepository, IMapper mapper, ILogger<GetInvoiceManagementCommandHandler> logger, IInvoicetypeRepository invoicetypeRepository, IPayeeRepository payeeRepository)
        {
            _invoiceManagementRepository = invoiceManagementRepository;
            _mapper = mapper;
            _logger = logger;
            _invoicetypeRepository = invoicetypeRepository;
            _payeeRepository = payeeRepository;
        }

        public async Task<ApiResult<PagingResult<IList<GetpageInvoiceManagementResponse>>>> Handle(GetInvoiceManagementCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 获取所有开票信息
                var invoiceManagements = await _invoiceManagementRepository.GetAllAsync();
                // 发票类型（外健）
                var Sourcetypes = await _invoicetypeRepository.GetAllAsync();
                // 发票类型（外健）
                var Payees = await _payeeRepository.GetAllAsync();

                // 外健链接
                var result = from InvoiceManagement in invoiceManagements
                             join Invoicetype in Sourcetypes on InvoiceManagement.InvoicetypeId equals Invoicetype.InvoicetypeId
                             join Payee in Payees on InvoiceManagement.PayeeId equals Payee.PayeeId
                             select new GetpageInvoiceManagementResponse
                             {
                                 Invoicemanagementid = InvoiceManagement.Invoicemanagementid,
                                 Invoicingnumber = InvoiceManagement.Invoicingnumber,
                                 Invoicetheme = InvoiceManagement.Invoicetheme,
                                 InvoicetypeId = InvoiceManagement.InvoicetypeId,//发票类型（外健）
                                 Invoicingdate = InvoiceManagement.Invoicingdate,
                                 PayeeId = InvoiceManagement.PayeeId,
                                 Invoiceamount = InvoiceManagement.Invoiceamount,
                                 Invoicenumber = InvoiceManagement.Invoicenumber,
                                 Invoicemanagementnotes = InvoiceManagement.Invoicemanagementnotes,
                                 InvoicetypeName = Invoicetype.InvoicetypeName, // 发票类型名称
                                 PayeeName = Payee.PayeeName // 开、收票方名称
                             };

          

                // 当前页的数据
                var currentData = _mapper.Map<IList<GetpageInvoiceManagementResponse>>(result.Skip(request.PageSize * (request.PageIndex - 1)).Take(request.PageSize).ToList());

                // 分页
                var pagingResult = new PagingResult<IList<GetpageInvoiceManagementResponse>>
                {
                    TotalCount = result.Count(),
                    TotalPage = Math.Ceiling(result.Count() / (double)request.PageSize),
                    Data = currentData
                };

                // 返回成功结果
                return ApiResult<PagingResult<IList<GetpageInvoiceManagementResponse>>>.Success(pagingResult, StatusCodeEnum.Success);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询失败");

                // 返回失败结果
                return ApiResult<PagingResult<IList<GetpageInvoiceManagementResponse>>>.Fail("查询失败：" + ex.Message, StatusCodeEnum.BadRequest);
            }
        }
    }
}
